<template>
  <div class="callback-container">
    <div class="callback-card">
      <div v-if="loading" class="loading-section">
        <div class="loading-spinner"></div>
        <p class="loading-text">正在处理钉钉登录信息，请稍候...</p>
      </div>

      <div v-else-if="error" class="error-section">
        <div class="error-icon">!</div>
        <h2 class="error-title">登录失败</h2>
        <p class="error-message">{{ error }}</p>
        <el-button type="primary" @click="goToLogin">返回登录页</el-button>
      </div>

      <div v-else class="success-section">
        <div class="success-icon">✓</div>
        <h2 class="success-title">登录成功</h2>
        <p class="welcome-message">欢迎回来，{{ phone }}！</p>
        <p class="redirect-text">{{ redirectMessage }}</p>
      </div>
    </div>

    <div class="dingtalk-footer">
      <div class="dingtalk-logo">
        <svg viewBox="0 0 1024 1024">
          <path d="M512 0C229.23 0 0 229.23 0 512s229.23 512 512 512 512-229.23 512-512S794.77 0 512 0z m269.312 676.096c-50.176 0-90.112-39.936-90.112-90.112s39.936-90.112 90.112-90.112 90.112 39.936 90.112 90.112-39.936 90.112-90.112 90.112zM380.416 429.568c-50.176 0-90.112-39.936-90.112-90.112s39.936-90.112 90.112-90.112 90.112 39.936 90.112 90.112-39.936 90.112-90.112 90.112z m243.712 0c-50.176 0-90.112-39.936-90.112-90.112s39.936-90.112 90.112-90.112 90.112 39.936 90.112 90.112-39.936 90.112-90.112 90.112zM242.688 676.096c-50.176 0-90.112-39.936-90.112-90.112s39.936-90.112 90.112-90.112 90.112 39.936 90.112 90.112-39.936 90.112-90.112 90.112z" fill="#1296DB"></path>
        </svg>
      </div>
      <p class="dingtalk-text">钉钉登录处理中</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const loading = ref(true)
const error = ref(null)
const phone = ref('')
const redirectPath = ref('/')

const redirectMessage = computed(() => {
  if (redirectPath.value === '/') {
    return '正在跳转到首页...'
  }
  return `正在跳转到 ${redirectPath.value}...`
})

onMounted(async () => {
  try {
    // 从URL参数中获取code和state
    const urlParams = new URLSearchParams(window.location.search)
    const code = urlParams.get('code')
    const state = urlParams.get('state')

    // 检查是否有错误参数
    if (urlParams.has('error')) {
      loading.value = false
      error.value = decodeURIComponent(urlParams.get('error'))
      return
    }

    // 验证必要参数
    if (!code || !state) {
      loading.value = false
      error.value = '缺少必要的授权参数'
      return
    }

    // 调用钉钉回调接口
    const response = await axios.get('http://127.0.0.1:8000/login/callback/', {
      params: {
        code,
        state
      }
    })

    // 检查响应状态
    if (response.status === 302) {
      // 处理重定向
      const redirectUrl = response.headers.location
      window.location.href = redirectUrl
      return
    }

    // 处理成功响应
   // ... 省略前面代码
if (response.data.code === 200) {
  const { token, retoken, user_info } = response.data

  // 存储token、手机号和userid
  localStorage.setItem('token', token)
  localStorage.setItem('retoken', retoken)
  localStorage.setItem('phone', user_info.phone)
  localStorage.setItem('user_id', user_info.userid)
  // 关键：存储role
  localStorage.setItem('role', user_info.role || 'user') // 默认user

  phone.value = user_info.phone

  // 关键：同步响应式role变量
     if (typeof updateRole === 'function') {
       updateRole()
     }

  // 模拟处理时间
     setTimeout(() => {
       loading.value = false
       setTimeout(() => {
         router.push('/').then(() => {
           window.location.reload()
         })
       }, 1000)
     }, 800)
    } else {
      throw new Error(response.data.msg || '登录失败')
    }
  } catch (err) {
    console.error('钉钉回调处理失败:', err)
    loading.value = false
    error.value = err.response?.data?.msg || err.message || '钉钉登录处理失败'
  }
})

const goToLogin = () => {
  // 清除处理标记
  localStorage.removeItem('processingDingtalkLogin')
  router.push('/login')
}
</script>

<style scoped>
.callback-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.callback-card {
  width: 500px;
  padding: 40px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
  text-align: center;
}

.loading-section, .error-section, .success-section {
  padding: 30px 0;
}

.loading-spinner {
  width: 60px;
  height: 60px;
  margin: 0 auto 20px;
  border: 5px solid #e0e0e0;
  border-top: 5px solid #1296DB;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 18px;
  color: #555;
  margin-top: 20px;
}

.error-icon, .success-icon {
  width: 80px;
  height: 80px;
  margin: 0 auto 20px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40px;
  font-weight: bold;
}

.error-icon {
  background-color: #ffebee;
  color: #f44336;
}

.success-icon {
  background-color: #e8f5e9;
  color: #4caf50;
}

.error-title, .success-title {
  font-size: 24px;
  margin-bottom: 15px;
}

.error-title {
  color: #f44336;
}

.success-title {
  color: #4caf50;
}

.error-message {
  color: #666;
  margin-bottom: 25px;
  font-size: 16px;
}

.welcome-message {
  font-size: 18px;
  color: #333;
  margin-bottom: 10px;
}

.redirect-text {
  color: #777;
  font-size: 14px;
}

.dingtalk-footer {
  margin-top: 40px;
  display: flex;
  align-items: center;
  color: #1296DB;
}

.dingtalk-logo {
  width: 36px;
  height: 36px;
  margin-right: 10px;
}

.dingtalk-text {
  font-size: 16px;
  font-weight: 500;
}
</style>